//
//  HMWelcomeViewController.swift
//  微博
//
//  Created by 郭鉴增 on 2016/12/9.
//  Copyright © 2016年 郭鉴增. All rights reserved.
//

import UIKit
import SDWebImage
//欢迎页面
class HMWelcomeViewController: UIViewController {

    //MARK: - 懒加载
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    private lazy var userImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "avatar_default_big"))
        //获取用户头像地址
        if let imageUrl = HMUserAccountViewModel.sharedUserAccount.userAccount?.avatar_large{
            imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "avatar_default_big"))
        }
        
        imageView.layer.cornerRadius = 45
        imageView.layer.masksToBounds = true
        
        return imageView
    }()
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        if let name = HMUserAccountViewModel.sharedUserAccount.userAccount?.name{
            label.text = "欢迎回来,\(name)"
        } else {
            label.text = "欢迎回来"
        }
        label.font = UIFont.systemFont(ofSize: 13)
        label.textColor = UIColor.darkGray
        //默认情况下,label透明
        label.alpha = 0
        
        return label
    }()
    
    //自定义视图
    override func loadView() {
        view = bgImageView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    //开启弹簧动画
    private func startAnimation() {
        userImageView.snp_updateConstraints { (make) in
            make.top.equalTo(view).offset(100)
        }
        UIView.animate(withDuration: 1, delay: 0.5, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
            
            self.view.layoutIfNeeded()
            
        }, completion: {(_) -> Void in
            
            UIView.animate(withDuration: 1, animations: { 
                self.messageLabel.alpha = 1
            }, completion: { (_) in
                //切换到主页控制器
                NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotifationName), object: nil)
            })
    
        })
    }
    
    //添加控件设置约束
    private func setupUI() {
        
        view.addSubview(userImageView)
        view.addSubview(messageLabel)
        
        userImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(300)
            make.size.equalTo(CGSize(width:90, height: 90))
            
        }
        messageLabel.snp_makeConstraints { (make) in
            make.top.equalTo(userImageView.snp_bottom).offset(10)
            make.centerX.equalTo(userImageView)
        }
        
    }
    
}
